﻿using log4net;
using Rainbow.model;
using Rainbow.core;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using LSFTP;
using System.Collections.Generic;
using System;
using LSFTP.model;
using System.Linq;
using System.Windows.Input;
using System.IO;
using Rainbow.view;
using System.ComponentModel;
using System.Diagnostics;
using Rainbow.common;
using System.Windows.Controls.Primitives;
using StatusBar = Rainbow.common.StatusBar;
using System.Text.RegularExpressions;
using System.Windows.Media;
using Rainbow.utils;
using System.Data.SQLite;
using Rainbow.view.dataConversion;


namespace Rainbow
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private ILog logger = null;
        private MainWindowViewModel windowViewModel = null;

        public MainWindow()
        {
            InitializeComponent();

            logger = LogManager.GetLogger(typeof(MainWindow));

            this.Loaded += new RoutedEventHandler(Window_Loaded);
            this.Unloaded += new RoutedEventHandler(Window_Unloaded);
            this.Closing += new CancelEventHandler(Window_Closing);

            this.menuConnect.Click += new RoutedEventHandler(menuConnect_Click);
            this.menuSetting.Click += new RoutedEventHandler(menuSetting_Click);
            this.menuClose.Click += new RoutedEventHandler(menuClose_Click);

            this.menuDataConversion.Click += new RoutedEventHandler(DataConversion_Click);

            this.menuHelpFile.Click += new RoutedEventHandler(menuHelpFile_Click);
            this.menuAbout.Click += new RoutedEventHandler(menuAbout_Click);

            this.toolConnect.Click += new RoutedEventHandler(menuConnect_Click);
            this.toolUnConnect.Click += new RoutedEventHandler(menuUnConnect_Click);
            this.toolDelete.Click += new RoutedEventHandler(Delete_Click);
            this.toolFolder.Click += new RoutedEventHandler(MakeDir_Click);
            this.toolRename.Click += new RoutedEventHandler(ReName_Click);
            this.toolDownload.Click += new RoutedEventHandler(DownLoad_Click);
            this.toolUploadFile.Click += new RoutedEventHandler(Upload_Click);
            this.toolUploadFolder.Click += new RoutedEventHandler(UploadFolder_Click);
            this.toolPrevious.Click += new RoutedEventHandler(Previous_Click);
            this.toolSearch.Click += new RoutedEventHandler(Search_Click);

            this.toolDataConversion.Click += new RoutedEventHandler(DataConversion_Click);


            this.tvPath.SelectedItemChanged += new RoutedPropertyChangedEventHandler<object>(Path_SelectedItemChanged);
            this.tvPath.PreviewMouseUp += new MouseButtonEventHandler(tvPath_PreviewMouseUp);

            this.lvPath.Drop += new DragEventHandler(lvPath_Drop);
            this.lvPath.PreviewDragOver += new DragEventHandler(lvPath_PreviewDragOver);
            this.lvPath.SelectionChanged += new SelectionChangedEventHandler(lvPath_SelectionChanged);
            //this.lvPath.MouseDoubleClick += new System.Windows.Input.MouseButtonEventHandler(lvPath_MouseDoubleClick);
            this.lvPath.PreviewMouseDoubleClick += new MouseButtonEventHandler(lvPath_MouseDoubleClick);


            this.menuDownLoad.Click += new RoutedEventHandler(DownLoad_Click);
            this.menuDelete.Click += new RoutedEventHandler(Delete_Click);
            this.menuMakeDir.Click += new RoutedEventHandler(MakeDir_Click);
            this.menuReName.Click += new RoutedEventHandler(ReName_Click);

            this.tbCurPath.PreviewKeyDown += new KeyEventHandler(CurPath_PreviewKeyDown);

            int rn = TW_App.Init();
            if(rn != 0)
            {
                string errMsg = "程序初始化失败";
                logger.ErrorFormat(errMsg);
                MessageBox.Show(errMsg,"错误",MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            windowViewModel = new MainWindowViewModel();
            this.DataContext = windowViewModel;

            this.statusBar.DataContext = TW_App.statusBarInfo;

            //TW_App.ftp = new SFTPClient("192.168.1.118", 22, "lushuai", "wojiushiwo");
            //TW_App.ftp = new SFTPClient("10.0.0.123", 22, "root", "root");
        }

        private void CurPath_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if(e.Key == Key.Enter) //判断是否回车
            {
                // 模糊检索文件列表
                string searchStr = this.tbCurPath.Text;

                if (windowViewModel.curPathNode == null) return;

                // 判断要搜索的内容是否与当前路径一致，如果一致取消搜索
                if (string.IsNullOrEmpty(searchStr)
                    ||searchStr.Equals(windowViewModel.curPathNode.path) 
                    || searchStr.Equals("/")) return;

                // 判断ftp是否连接
                if (TW_App.ftp == null || !TW_App.ftp.GetConnectStatus())
                {
                    MessageBox.Show("SFTP未连接，请连接后操作", "提示", MessageBoxButton.OK, MessageBoxImage.Information);

                    return;
                }

                ProgressingDlg progressingDlg = new ProgressingDlg("检索", "努力查找中...", new DoWorkEventHandler((object s, DoWorkEventArgs args) =>
                {
                    try
                    {
                        // 获取全部文件
                        List<FTPFileInfo> list = TW_App.ftp.GetFileInfoList(windowViewModel.curPathNode.path, "*.*", true, false);

                        App.Current.Dispatcher.InvokeAsync((Action)(() =>
                        {
                            windowViewModel.CurPaths.Clear();
                            list.ForEach(x =>
                            {
                                if (x.Name.IndexOf(searchStr) >= 0)
                                {
                                    windowViewModel.CurPaths.Add(new model.FileInfoViewModel(x));
                                }
                            });
                        }));
                    }
                    catch (Exception ex)
                    {
                        logger.ErrorFormat("模糊检索数据异常:{0}", ex.Message);
                    }
                }));
                progressingDlg.Owner= this;
                progressingDlg.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                progressingDlg.ShowDialog();

                // 阻止事件进一步传播
                e.Handled = true;
            }
        }

        /// <summary>
        /// 断开链接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void menuUnConnect_Click(object sender, RoutedEventArgs e)
        {
            if (TW_App.ftp == null || !TW_App.ftp.GetConnectStatus())
            {
                MessageBox.Show("SFTP未连接，请连接后操作", "提示", MessageBoxButton.OK, MessageBoxImage.Information);

                return;
            }
            TW_App.ftp.Disconnect();
            TW_App.ftp = null;
            StatusBar.print(MessageType.Error, "连接已断开,请重新连接");
            windowViewModel.ReLoad();
            windowViewModel.toolBarLinkIp = "未连接";
        }

        /// <summary>
        /// 检索
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void Search_Click(object sender, RoutedEventArgs e)
        {
            if (TW_App.ftp == null)
            {
                MessageBox.Show("SFTP未连接，请连接后操作", "提示", MessageBoxButton.OK, MessageBoxImage.Information);

                return;
            }

            windowViewModel.CurPaths.Clear();
            PathTreeNode ptn = this.tvPath.SelectedItem as PathTreeNode;
            if (ptn == null ) { MessageBox.Show("请选择要检索的目录", "提示", MessageBoxButton.OK, MessageBoxImage.Information); return; }

            DateTime? strTime = dpStartDate.SelectedDate;
            DateTime? endTime = dpEndDate.SelectedDate;
            if (strTime> endTime) { MessageBox.Show("开始时间不得大于结束时间", "提示", MessageBoxButton.OK, MessageBoxImage.Information); return; }

            ProgressingDlg progressingDlg = new ProgressingDlg("检索", "文件检索中...", new DoWorkEventHandler((object s, DoWorkEventArgs args) =>
            {

                List<FTPFileInfo> files = TW_App.ftp.GetFileInfoList(ptn.path, "*.*", true, false);
                //Console.WriteLine(ptn.path);//输出当前地址

                ObservableCollection<model.FileInfoViewModel> infos = new ObservableCollection<model.FileInfoViewModel>();

                foreach (FTPFileInfo file in files)
                {
                    if (!file.IsDirectory) continue;
                    if (!Regex.IsMatch(file.Name, @"^((((1[6-9]|[2-9]\d)\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})-0?2-(0?[1-9]|1\d|2[0-9]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-))$")) continue;

                    //取出文件名中的日期
                    //int startIndex = file.Name.LastIndexOf("_");
                    //if (startIndex == -1) continue;
                    //// 截取从开始符号后的10个字符（注意：如果字符串长度不够，则需要截取到字符串末尾）  
                    //int endIndex = Math.Min(startIndex + 10, file.Name.Length);
                    //string dateString = file.Name.Substring(startIndex + 1, endIndex - (startIndex));
                    //Console.WriteLine(file.Name + "***" + dateString);
                    string format = "yyyy-MM-dd";
                    DateTime dateTimeValue;
                    if (!DateTime.TryParseExact(file.Name, format, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out dateTimeValue)) continue;

                    //if (DateTime.TryParseExact(file.Name, format, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out dateTimeValue))
                    //{
                    //    Console.WriteLine("转换后的日期和时间: " + dateTimeValue);
                    //}
                    //else
                    //{
                    //    Console.WriteLine("字符串无法按照指定的格式转换为日期和时间");
                    //}

                    //判断日期是否在区间内

                    //Console.WriteLine("开始: " + dpStartDate.SelectedDate);
                    //Console.WriteLine("终了: " + dpEndDate.SelectedDate);


                    if (endTime >= dateTimeValue && dateTimeValue >= strTime)
                    {
                        Console.WriteLine("符合");
                        infos.Add(new model.FileInfoViewModel(file));
                    }
                    else
                    {
                        Console.WriteLine("不符合" + dateTimeValue + file.Name);
                        continue;
                    }
                }
                App.Current.Dispatcher.InvokeAsync((Action)(() =>
                {
                    windowViewModel.CurPaths = new ObservableCollection<model.FileInfoViewModel>(infos.OrderByDescending(item => item.IsDirectory));
                }));
            }));

            progressingDlg.Owner = this;
            progressingDlg.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            progressingDlg.ShowDialog();
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Upload_Click(object sender, RoutedEventArgs e)
        {
            if (TW_App.ftp == null || !TW_App.ftp.GetConnectStatus())
            {
                MessageBox.Show("SFTP未连接，请连接后操作", "提示", MessageBoxButton.OK, MessageBoxImage.Information);

                return;
            }
            if (tvPath.SelectedItem == null)
            {
                MessageBox.Show("请选择远程路径");
                return;
            }

            System.Windows.Forms.OpenFileDialog openFileDialog = new System.Windows.Forms.OpenFileDialog();
            openFileDialog.Title = "请选择需要上传的文件";
            openFileDialog.Multiselect = true;
            System.Windows.Forms.DialogResult result = openFileDialog.ShowDialog();

            if(System.Windows.Forms.DialogResult.OK == result)
            {
                //获取文件选中列表
                string[] files = openFileDialog.FileNames;
                //foreach (var item in files)
                //{
                //    Console.WriteLine(item);
                //}
                //ProgressingDlg progressingDlg = new ProgressingDlg("上传", "文件上传中...", new DoWorkEventHandler((object s, DoWorkEventArgs args) =>
                //{
                //App.Current.Dispatcher.InvokeAsync((Action)(() =>
                //{
                List<string[]> upFiles = new List<string[]>(); ;

                        try
                        {
                            PathTreeNode node = tvPath.SelectedItem as PathTreeNode;
                            if (node == null) return;

                            if (files == null || files.Length == 0) return;

                            string rootLocalPath = files[0].Substring(0, files[0].LastIndexOf("\\"));
                            string remotePath = node.path;
                            remotePath = remotePath.Replace("/", "\\");

                            // 将文件路径添加到ListView中
                            foreach (var file in files)
                            {
                                string localFileName = file.Substring(file.LastIndexOf("\\"));
                                string remoteFile = remotePath + localFileName;
                                if (System.IO.File.Exists(file))
                                {
                                    //TW_App.ftp.Upload(file, remotePath);
                                    upFiles.Add(new string[] { localFileName.TrimStart('\\'), file, remotePath });
                                }
                            }

                            UploadFileDlg dlg = new UploadFileDlg(upFiles, TW_App.ftp as SFTPClient);
                            dlg.Owner = this;
                            dlg.WindowStartupLocation = WindowStartupLocation.CenterOwner;

                            bool? res = dlg.ShowDialog();
                            if (res == true)
                            {
                                StatusBar.print(MessageType.Info, "上传完成");
                            }
                            else
                            {
                                StatusBar.print(MessageType.Info, "已取消上传");
                            }


                            // 刷新页面
                            PathTreeNode ptn = tvPath.SelectedItem as PathTreeNode;

                            if (ptn == null) return;

                            RefreshListView(ptn);

                            //StatusBar.print(MessageType.Info, "文件上传成功");
                        }
                        catch (Exception)
                        {
                            StatusBar.print(MessageType.Error, "文件上传失败");
                        }

                    //}));
                //}));

                //progressingDlg.Owner = this;
                //progressingDlg.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                //progressingDlg.ShowDialog();



            }


        }

        /// <summary>
        /// 上传文件夹
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UploadFolder_Click(object sender, RoutedEventArgs e)
        {
            if (TW_App.ftp == null || !TW_App.ftp.GetConnectStatus())
            {
                MessageBox.Show("SFTP未连接，请连接后操作", "提示", MessageBoxButton.OK, MessageBoxImage.Information);

                return;
            }
            if (tvPath.SelectedItem == null)
            {
                MessageBox.Show("请选择远程路径");
                return;
            }

            System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
            dialog.Description = "请选择需要上传的文件夹";
            

            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                //获取选中的文件夹地址
                string path = dialog.SelectedPath; // "e:/go"

                PathTreeNode node = tvPath.SelectedItem as PathTreeNode;
                if (node == null) return;

                //ProgressingDlg progressingDlg = new ProgressingDlg("上传", "文件上传中...", new DoWorkEventHandler((object s, DoWorkEventArgs args) =>
                //{
                    try
                    {
                        if (string.IsNullOrEmpty(path)) return;

                        string rootLocalPath = path.Substring(0,path.LastIndexOf("\\")); 
                        string remotePath = node.path;
                        remotePath = remotePath.Replace("/", "\\");

                        // 将文件路径添加到ListView中

                        string localFileName = path.Substring(path.LastIndexOf("\\")).Replace("\\", "");
                        string remoteFile = (remotePath + "\\" + localFileName).Replace("\\\\","\\");

                        TW_App.ftp.MakeDirectory(remoteFile.Replace("\\", "/"));

                        List<string> list = new List<string>();
                        getDirectory(list, path);
                        list = list.OrderBy(x => x.Length).ToList();

                    List<string[]> upFiles = new List<string[]>();
                        foreach (var item in list)
                        {
                            string rPath = item.Replace(rootLocalPath, "");
                            string rFile = (remotePath + rPath);

                            if (System.IO.File.Exists(item))
                            {
                                rFile = rFile.Substring(0, rFile.LastIndexOf("\\"));
                            //TW_App.ftp.Upload(item, rFile);
                            string fileName = item.Substring(item.LastIndexOf("\\") + 1);
                            upFiles.Add(new string[] {fileName,  item, rFile });
                            }
                            else if (Directory.Exists(item))
                            {
                                TW_App.ftp.MakeDirectory(rFile.Replace("\\", "/"));
                            }
                        }

                    UploadFileDlg dlg = new UploadFileDlg(upFiles, TW_App.ftp as SFTPClient);
                    dlg.Owner = this;
                    dlg.WindowStartupLocation = WindowStartupLocation.CenterOwner;

                    bool? res = dlg.ShowDialog();
                    if (res == true)
                    {
                        StatusBar.print(MessageType.Info, "上传完成");
                    }
                    else
                    {
                        StatusBar.print(MessageType.Info, "已取消上传");
                    }

                    //App.Current.Dispatcher.InvokeAsync((Action)(() =>
                    //    {
                            // 刷新TreeView
                            PathTreeNode tNode = new PathTreeNode();
                            tNode.Name = localFileName;
                            tNode.path = remoteFile.Replace("\\", "/").Replace("//","/");
                            tNode.ParentNode = node;
                            if(node.Children.Count == 1 && node.Children[0].Name == null)
                            {
                                node.Children.Clear();
                            }
                            node.Children.Add(tNode);
                        //}));
                            
                        

                        //App.Current.Dispatcher.InvokeAsync((Action)(() =>
                        //{
                            // 刷新页面
                            PathTreeNode ptn = tvPath.SelectedItem as PathTreeNode;

                            if (ptn == null) return;

                            RefreshListView(ptn);

                            //StatusBar.print(MessageType.Info, "文件上传成功");
                        //}));
                    }
                    catch (Exception)
                    {
                        //App.Current.Dispatcher.InvokeAsync((Action)(() =>
                        //{
                            StatusBar.print(MessageType.Error, "文件上传失败");
                        //}));
                    }
                //}));

                //progressingDlg.Owner = this;
                //progressingDlg.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                //progressingDlg.ShowDialog();
            }

        }


        #region 用户交互

        private void tvPath_PreviewMouseUp(object sender, MouseButtonEventArgs e)
        {
            // 判断是不是点击的TextBlock(判断点击的是展开折叠按钮还是文本）
            ToggleButton toggleButton = e.OriginalSource as ToggleButton;
            if (toggleButton != null) return;

            TreeView tv = sender as TreeView;
            if (null == tv) return;
            if(tv.SelectedItem == null) return;

            PathTreeNode node = tv.SelectedItem as PathTreeNode;

            if (node == null) return;

            FrameworkElement rootElement = (FrameworkElement)lvPath;
            CheckBox checkBox = FindVisualChild<CheckBox>(rootElement, "cbAllSelected");

            if (checkBox != null)
            {
                checkBox.IsChecked = false;
            }

            RefreshListView(node);
        }
        private void menuConnect_Click(object sender, RoutedEventArgs e)
        {
            ConnectDlg dlg = new ConnectDlg();
            dlg.Owner = this;
            dlg.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            bool? result = dlg.ShowDialog();

            if (result == true)
            {
                windowViewModel.connectInfo = dlg.windowViewModel.info.Clone();
                if (TW_App.ftp != null)
                    TW_App.ftp.Disconnect();

                windowViewModel.ReLoad();

                ProgressingDlg progressingDlg = new ProgressingDlg("连接", "连接中...", new DoWorkEventHandler((object s, DoWorkEventArgs args) =>
                {
                    try
                    {
                        TW_App.ftp = new SFTPClient(windowViewModel.connectInfo.host, windowViewModel.connectInfo.port, windowViewModel.connectInfo.username, windowViewModel.connectInfo.passPhrase);
                        TW_App.ftp.Connect();

                        
                        if (!TW_App.ftp.GetConnectStatus())
                        {
                            App.Current.Dispatcher.InvokeAsync((Action)(() =>
                            {
                                //MessageBox.Show("服务器连接失败，请检查网络是否正常","错误",MessageBoxButton.OK, MessageBoxImage.Error);
                                StatusBar.print(MessageType.Error, "服务器连接失败，请检测网络是否正常");
                            }));
                            return;
                        }
                        else
                        {
                            List<string> directorys = TW_App.ftp.GetDirectoryList(windowViewModel.RootNode.path);
                            App.Current.Dispatcher.InvokeAsync((Action)(() =>
                            {                    
                                windowViewModel.RootNode.Children.Clear();
                                foreach (var item in directorys)
                                {
                                    PathTreeNode node = new PathTreeNode();
                                    node.Name = item.Substring(item.LastIndexOf('/') + 1);
                                    node.path = item;
                                    node.ParentNode = windowViewModel.RootNode;
                                    windowViewModel.RootNode.Children.Add(node);
                                }
                                string msg = string.Format("连接成功");
                                StatusBar.print(MessageType.Info, msg);
                                //this.linkIP.Text = windowViewModel.connectInfo.host + windowViewModel.connectInfo.port + "---- 正在连接";
                                windowViewModel.toolBarLinkIp = windowViewModel.connectInfo.host + " 已连接";
                            }));

                        }
                    }
                    catch (Exception ex)
                    {
                        App.Current.Dispatcher.InvokeAsync((Action)(() =>
                        {
                            StatusBar.print(MessageType.Error, ex.Message);
                        }));
                    }
                }));

                progressingDlg.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                progressingDlg.Owner = this;
                progressingDlg.ShowDialog();

            }
        }

        private void menuSetting_Click(object sender, RoutedEventArgs e)
        {
            GlobalSettingDlg dlg = new GlobalSettingDlg();
            dlg.Owner = this;
            dlg.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            bool? result = dlg.ShowDialog();
            if (result == false) return;

            GlobalSetting globalSetting = TW_App.globalSetting;
            globalSetting.rootPath = dlg.windowViewModel.globalSetting.rootPath;
            globalSetting.downloadThreadNum = dlg.windowViewModel.globalSetting.downloadThreadNum;
            globalSetting.uploadThreadNum = dlg.windowViewModel.globalSetting.uploadThreadNum;
            
            globalSetting.Save();

            windowViewModel.ReLoad();

            

            if(TW_App.ftp != null && TW_App.ftp.GetConnectStatus())
            {
                List<string> directorys = TW_App.ftp.GetDirectoryList(windowViewModel.RootNode.path);
                windowViewModel.RootNode.Children.Clear();
                foreach (var item in directorys)
                {
                    PathTreeNode node = new PathTreeNode();
                    node.Name = item.Substring(item.LastIndexOf('/') + 1);
                    node.path = item;
                    node.ParentNode = windowViewModel.RootNode;
                    windowViewModel.RootNode.Children.Add(node);
                }
            }

            string msg = string.Format("设置成功");
            StatusBar.print(MessageType.Info, msg);
        }

        private void menuClose_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void menuHelpFile_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Process helpProcess = new Process();
                helpProcess.StartInfo.FileName = Directory.GetCurrentDirectory() + "\\help\\使用说明.pdf";
                helpProcess.StartInfo.Verb = "Open";
                helpProcess.StartInfo.CreateNoWindow = true;
                helpProcess.Start();
            }
            catch (Exception)
            {

            }
        }

        private void menuAbout_Click(object sender, RoutedEventArgs e)
        {
            AboutDlg dlg = new AboutDlg();
            dlg.Owner = this;
            dlg.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            dlg.ShowDialog();
        }

        private void lvPath_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            ListView listView = sender as ListView;
            model.FileInfoViewModel item = listView.SelectedItem as model.FileInfoViewModel;
            if (item != null)
            {
                if (item.IsDirectory)
                {
                    windowViewModel.CurPaths.Clear();
                    try
                    {
                        if (TW_App.ftp == null || !TW_App.ftp.GetConnectStatus())
                        {
                            MessageBox.Show("SFTP未连接，请连接后操作", "提示", MessageBoxButton.OK, MessageBoxImage.Information);

                            return;
                        }

                        List<FTPFileInfo> files = TW_App.ftp.GetFileInfoList(item.FullName);
                        ObservableCollection<model.FileInfoViewModel> infos = new ObservableCollection<model.FileInfoViewModel>();
                        foreach (FTPFileInfo file in files)
                        {
                            if (".".Equals(file.Name) || "..".Equals(file.Name))
                                continue;
                            infos.Add(new model.FileInfoViewModel(file));
                        }
                        windowViewModel.CurPaths = new ObservableCollection<model.FileInfoViewModel>(infos.OrderByDescending(v => v.IsDirectory));

                        // 修改TreeView选择项
                        //PathTreeNode tvNode = this.tvPath.SelectedItem as PathTreeNode;
                        //if (tvNode == null) return;
                        //tvNode.IsSelected = false;
                        //tvNode.IsExpanded = true;
                        //foreach (var item1 in tvNode.Children)
                        //{
                        //    PathTreeNode n = item1 as PathTreeNode;
                        //    if(n.path == item.FullName)
                        //    {
                        //        windowViewModel.curPathNode = n;
                        //        n.IsSelected = true;
                        //        n.IsExpanded = true;
                        //    }
                        //}                        

                        FrameworkElement rootElement = (FrameworkElement)lvPath;
                        CheckBox checkBox = FindVisualChild<CheckBox>(rootElement, "cbAllSelected");

                        if(checkBox != null)
                        {
                            checkBox.IsChecked = false;
                        }

                        SetTreeSelectNode(item.FullName);
                    }
                    catch (Exception)
                    {

                    }
                }
            }
        }

        // 辅助方法，用于在VisualTree中查找控件
        public static T FindVisualChild<T>(DependencyObject obj, string name) where T : DependencyObject
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(obj, i);
                if (child != null && child is T && (((T)child).GetValue(NameProperty) as string) == name)
                {
                    return (T)child;
                }
                else
                {
                    T childOfChild = FindVisualChild<T>(child, name);
                    if (childOfChild != null)
                    {
                        return childOfChild;
                    }
                }
            }
            return null;
        }

        private void SetTreeSelectNode(string FullName)
        {
            searchNode(windowViewModel.RootNode, FullName, 0);
        }

        private void searchNode(PathTreeNode node, string FullName, int index)
        {
            string[] names = FullName.Split('/');
            if (node.path.Equals(FullName))
            {
                node.IsSelected = true;
                return;
            }
            if (index == names.Length - 1) return;

            index++;
            foreach (PathTreeNode item1 in node.Children)
            {
                if (item1.Name.Equals(names[index]))
                {
                    item1.IsExpanded = true;
                    searchNode(item1, FullName, index);
                }
            }
        }

        // 拖放文件事件处理
        private void lvPath_Drop(object sender, DragEventArgs e)
        {
            // 获取拖放的文件列表
            var files = (e.Data.GetData(DataFormats.FileDrop) as string[]) ?? new string[0];

            if(tvPath.SelectedItem ==  null) {
                MessageBox.Show("请选择远程路径");
                return; }

            if (TW_App.ftp == null || !TW_App.ftp.GetConnectStatus())
            {
                MessageBox.Show("SFTP未连接，请连接后操作", "提示", MessageBoxButton.OK, MessageBoxImage.Information);

                return;
            }

            PathTreeNode node = tvPath.SelectedItem as PathTreeNode;
            if (node == null) return;

            //ProgressingDlg progressingDlg = new ProgressingDlg("上传", "文件上传中...", new DoWorkEventHandler((object s, DoWorkEventArgs args) =>
            //{
                try
                {
                    if (files == null || files.Length == 0) return;

                    string rootLocalPath = files[0].Substring(0, files[0].LastIndexOf("\\"));
                    string remotePath = node.path;
                    remotePath = remotePath.Replace("/", "\\");

                    List<string[]> upFiles = new List<string[]>();

                    // 将文件路径添加到ListView中
                    foreach (var file in files)
                    {
                        string localFileName = file.Substring(file.LastIndexOf("\\")).Replace("\\","");
                        string remoteFile = remotePath + "\\" +  localFileName;
                        if (System.IO.File.Exists(file))
                        {
                            //TW_App.ftp.Upload(file, remotePath);
                            upFiles.Add(new string[] { localFileName, file, remotePath });
                        }
                        else if (Directory.Exists(file))
                        {
                            TW_App.ftp.MakeDirectory(remoteFile.Replace("\\", "/"));

                            List<string> list = new List<string>();
                            getDirectory(list, file);
                            list = list.OrderBy(x => x.Length).ToList();
                            foreach (var item in list)
                            {
                                string rPath = item.Replace(rootLocalPath, "");
                                string rFile = (remotePath + rPath);

                                if (System.IO.File.Exists(item))
                                {
                                    rFile = rFile.Substring(0, rFile.LastIndexOf("\\"));
                                    //TW_App.ftp.Upload(item, rFile);
                                    string fileName = item.Substring(item.LastIndexOf("\\")+1);
                                    upFiles.Add(new string[] { fileName, item, rFile });
                                }
                                else if (Directory.Exists(item))
                                {
                                    TW_App.ftp.MakeDirectory(rFile.Replace("\\", "/"));
                                }
                            }
                        }
                        else
                        {
                            logger.Error("拖拽上传的文件路径不存在。");
                        }

                        if (Directory.Exists(file))
                        {
                            //App.Current.Dispatcher.InvokeAsync((Action)(() =>
                            //{
                                // 刷新TreeView
                                PathTreeNode tNode = new PathTreeNode();
                                tNode.Name = localFileName;
                                tNode.path = remoteFile.Replace("\\", "/").Replace("//","/");
                                tNode.ParentNode = node;

                                if(node.Children.Count == 1 && node.Children[0].Name == null)
                                {
                                    node.Children.Clear();
                                }

                                node.Children.Add(tNode);
                            //}));
                        }
                    }

                    UploadFileDlg dlg = new UploadFileDlg(upFiles,TW_App.ftp as SFTPClient);
                    dlg.Owner = this;
                    dlg.WindowStartupLocation = WindowStartupLocation.CenterOwner;

                    bool? res = dlg.ShowDialog();
                    if (res == true)
                    {
                        StatusBar.print(MessageType.Info, "上传完成");
                    }
                    else
                    {
                        StatusBar.print(MessageType.Info, "已取消上传");
                    }

                    //App.Current.Dispatcher.InvokeAsync((Action)(() =>
                    //{
                        // 刷新页面
                        PathTreeNode ptn = tvPath.SelectedItem as PathTreeNode;

                        if (ptn == null) return;

                        RefreshListView(ptn);

                        //StatusBar.print(MessageType.Info, "文件上传成功");
                    //}));
                }
                catch (Exception)
                {
                    //App.Current.Dispatcher.InvokeAsync((Action)(() =>
                    //{
                        StatusBar.print(MessageType.Error, "文件上传失败");
                    //}));
                }  
            //}));

            //progressingDlg.Owner = this;
            //progressingDlg.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            //progressingDlg.ShowDialog();
        }

        // 允许拖放
        private void lvPath_PreviewDragOver(object sender, DragEventArgs e)
        {
            e.Handled = true;
            e.Effects = DragDropEffects.Copy;
        }

        private void lvPath_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            foreach (model.FileInfoViewModel item in e.RemovedItems)
            {
                item.IsSelected = false;
            }
            foreach (model.FileInfoViewModel item in e.AddedItems)
            {
                item.IsSelected = true;
            }
        }

        private void Path_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            //PathTreeNode oldNode = e.OriginalSource as PathTreeNode;
            //PathTreeNode newNode = e.NewValue as PathTreeNode;

            //windowViewModel.CurPaths.Clear();
            //try
            //{
            if (TW_App.ftp == null || !TW_App.ftp.GetConnectStatus()) 
            {
                MessageBox.Show("SFTP未连接，请连接后操作","提示",MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            //    List<FTPFileInfo> files = TW_App.ftp.GetFileInfoList(newNode.path);
            //    ObservableCollection<FileInfoViewModel> infos = new ObservableCollection<FileInfoViewModel>();
            //    foreach (FTPFileInfo file in files)
            //    {
            //        if (".".Equals(file.Name) || "..".Equals(file.Name))
            //            continue;
            //        infos.Add(new FileInfoViewModel(file));
            //    }
            //    windowViewModel.CurPaths = new ObservableCollection<FileInfoViewModel>(infos.OrderByDescending(item => item.IsDirectory));
            //}
            //catch (Exception)
            //{

            //}

            windowViewModel.curPathNode = this.tvPath.SelectedItem as PathTreeNode;

        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                //List<string> directorys = TW_App.ftp.GetDirectoryList("\\");
                //windowViewModel.RootNode.Children.Clear();
                //foreach (var item in directorys)
                //{
                //    PathTreeNode node = new PathTreeNode();
                //    node.Name = item.Substring(item.LastIndexOf('/')+1);
                //    node.path = item;
                //    windowViewModel.RootNode.Children.Add(node);
                //}
            }
            catch(Exception)
            {
                logger.ErrorFormat("连接服务器失败");
            }

        }

        private void Window_Unloaded(object sender, RoutedEventArgs e)
        {
            
        }


        private void Window_Closing(object sender, CancelEventArgs e)
        {
            if (TW_App.ftp != null && TW_App.ftp.GetConnectStatus())
                TW_App.ftp.Disconnect();
        }

        private void ToolBar_Loaded(object sender, RoutedEventArgs e)
        {
            //去掉ToolBar右边默认的扩展图标
            ToolBar toolBar = sender as ToolBar;

            var overflowGrid = toolBar.Template.FindName("OverflowGrid", toolBar) as FrameworkElement;

            if (overflowGrid != null)
            {
                overflowGrid.Visibility = Visibility.Collapsed;
            }
            var mainPanelBorder = toolBar.Template.FindName("MainPanelBorder", toolBar) as FrameworkElement;

            if (mainPanelBorder != null)
            {
                mainPanelBorder.Margin = new Thickness(0);
            }
        }


        private void DownLoad_Click(object sender, RoutedEventArgs e)
        {
            //MenuItem munuItem = sender as MenuItem;
            //if (munuItem == null) return;
            //System.Collections.IList items = (munuItem.CommandParameter) as System.Collections.IList;
            if (TW_App.ftp == null || !TW_App.ftp.GetConnectStatus())
            {
                MessageBox.Show("SFTP未连接，请连接后操作", "提示", MessageBoxButton.OK, MessageBoxImage.Information);

                return;
            }
            var fileViewModels = lvPath.SelectedItems.Cast<model.FileInfoViewModel>();

            if (fileViewModels == null || lvPath.SelectedItems.Count <1){
                MessageBox.Show("请选择需要下载的文件");
                return; }

            List<FTPFileInfo> files = new List<FTPFileInfo>();
            //for (int i = 0; i < fileViewModels.Length; i++)
            //{
            //    files.Add(fileViewModels[i].ToInfo());
            //}
            foreach (var item in fileViewModels)
            {
                files.Add(item.ToInfo());
            }
            using (System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog())
            {
                dialog.Description = "请选择一个文件夹";
                System.Windows.Forms.DialogResult result = dialog.ShowDialog();

                if (result == System.Windows.Forms.DialogResult.OK)
                {
                    string selectedFolder = dialog.SelectedPath;

                    DownloadFileDlg dlg = new DownloadFileDlg(files, selectedFolder, TW_App.ftp as SFTPClient);
                    dlg.Owner = this;
                    dlg.WindowStartupLocation = WindowStartupLocation.CenterOwner;

                    bool? res = dlg.ShowDialog();
                    if(res == true)
                    {
                        StatusBar.print(MessageType.Info, "下载完成");
                    }
                    else
                    {
                        StatusBar.print(MessageType.Info, "已取消下载");
                    }
                    //string selectedFolder = dialog.SelectedPath;
                    //// 处理选中的文件夹，例如显示在文本框中
                    //// yourTextBox.Text = selectedFolder;
                    //ProgressingDlg progressingDlg = new ProgressingDlg("下载","下载中...",new DoWorkEventHandler((object s, DoWorkEventArgs args) =>
                    //{
                    //    try
                    //    {
                    //        TW_App.ftp.Download(files, selectedFolder);
                    //        App.Current.Dispatcher.InvokeAsync((Action)(() =>
                    //        {
                    //            StatusBar.print(MessageType.Info, "下载成功");
                    //        }));
                    //    }
                    //    catch (Exception ex)
                    //    {
                    //        logger.ErrorFormat("文件下载失败：{0}", ex.Message);
                    //    }
                    //}));
                    //progressingDlg.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                    //progressingDlg.Owner = this;
                    //progressingDlg.ShowDialog();
                }
            }

        }

        private void Delete_Click(object sender, RoutedEventArgs e)
        {
            //MenuItem munuItem = sender as MenuItem;
            //if (munuItem == null) return;
            //System.Collections.IList items = (munuItem.CommandParameter) as System.Collections.IList;

            //var fileViewModels = items.Cast<FileInfoViewModel>();

            //if (fileViewModels == null) return;

            List<FTPFileInfo> files = new List<FTPFileInfo>();
            //for (int i = 0; i < fileViewModels.Length; i++)
            //{
            //    files.Add(fileViewModels[i].ToInfo());
            //}
            //foreach (var item in fileViewModels)
            //{
            //    files.Add(item.ToInfo());
            //}
            if (TW_App.ftp == null || !TW_App.ftp.GetConnectStatus())
            {
                MessageBox.Show("SFTP未连接，请连接后操作", "提示", MessageBoxButton.OK, MessageBoxImage.Information);

                return;
            }
            if (lvPath.SelectedItems == null || lvPath.SelectedItems.Count ==0 ) {
                MessageBox.Show("请选中要删除的文件", "提示", MessageBoxButton.YesNo);
                return;
            }

            foreach (model.FileInfoViewModel item in lvPath.SelectedItems)
            {
                files.Add(item.ToInfo());
            }




            MessageBoxResult result = MessageBox.Show("确认要删除选中数据吗？", "删除确认", MessageBoxButton.YesNo, MessageBoxImage.Question);
            if(result == MessageBoxResult.No) return;

            // yourTextBox.Text = selectedFolder;
            ProgressingDlg progressingDlg = new ProgressingDlg("删除", "删除中...", new DoWorkEventHandler((object s, DoWorkEventArgs args) =>
            {
                try
                {
                    App.Current.Dispatcher.InvokeAsync((Action)(() =>
                    {
                        if (TW_App.ftp == null || !TW_App.ftp.GetConnectStatus())
                        {
                            MessageBox.Show("SFTP未连接，请连接后操作", "提示", MessageBoxButton.OK, MessageBoxImage.Information);

                            return;
                        }

                        files.ForEach(item =>
                        {
                            if(item.IsDirectory)
                            {
                                TW_App.ftp.DeleteDirectory(item.FullName);
                            }
                            else
                            {
                                TW_App.ftp.DeleteFile(item.FullName);
                            }

                            // 删除ListView中的文件
                            model.FileInfoViewModel fileInfoViewModel = windowViewModel.CurPaths.Where(x => x.FullName == item.FullName).FirstOrDefault();
                            if(fileInfoViewModel != null)
                            {
                                windowViewModel.CurPaths.Remove(fileInfoViewModel);
                            }
                            // 删除TreeView项
                            PathTreeNode tvNode = this.tvPath.SelectedItem as PathTreeNode;
                            PathTreeNode deleteNode = null;
                            foreach (var item1 in tvNode.Children)
                            {
                                PathTreeNode n = item1 as PathTreeNode;
                                if (n.path == item.FullName)
                                {
                                    deleteNode = item1 as PathTreeNode;
                                }
                            }
                            if(deleteNode != null )
                            {
                                tvNode.Children.Remove(deleteNode);
                            }

                        });


                        StatusBar.print(MessageType.Info, "删除成功");
                    }));
                }
                catch (Exception ex)
                {
                    logger.ErrorFormat("文件删除失败：{0}", ex.Message);
                }
            }));
            progressingDlg.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            progressingDlg.Owner = this;
            progressingDlg.ShowDialog();
                
            
        }

        //private void ToolDelete_Click(object sender, RoutedEventArgs e)
        //{
        //    ButtonEx butten = sender as ButtonEx;
        //    if (butten == null) return;
        //    System.Collections.IList items = (butten.CommandParameter) as System.Collections.IList;

        //    var fileViewModels = items.Cast<FileInfoViewModel>();

        //    if (fileViewModels == null) return;

        //    List<FTPFileInfo> files = new List<FTPFileInfo>();
        //    //for (int i = 0; i < fileViewModels.Length; i++)
        //    //{
        //    //    files.Add(fileViewModels[i].ToInfo());
        //    //}
        //    foreach (var item in fileViewModels)
        //    {
        //        files.Add(item.ToInfo());
        //    }

        //    MessageBoxResult result = MessageBox.Show("确认要删除选中数据吗？", "删除确认", MessageBoxButton.YesNo, MessageBoxImage.Question);
        //    if (result == MessageBoxResult.No) return;

        //    // yourTextBox.Text = selectedFolder;
        //    ProgressingDlg progressingDlg = new ProgressingDlg("删除", "删除中...", new DoWorkEventHandler((object s, DoWorkEventArgs args) =>
        //    {
        //        try
        //        {
        //            App.Current.Dispatcher.InvokeAsync((Action)(() =>
        //            {
        //                if (TW_App.ftp == null || !TW_App.ftp.GetConnectStatus()) return;

        //                files.ForEach(item =>
        //                {
        //                    if (item.IsDirectory)
        //                    {
        //                        TW_App.ftp.DeleteDirectory(item.FullName);
        //                    }
        //                    else
        //                    {
        //                        TW_App.ftp.DeleteFile(item.FullName);
        //                    }

        //                    // 删除ListView中的文件
        //                    FileInfoViewModel fileInfoViewModel = windowViewModel.CurPaths.Where(x => x.FullName == item.FullName).FirstOrDefault();
        //                    if (fileInfoViewModel != null)
        //                    {
        //                        windowViewModel.CurPaths.Remove(fileInfoViewModel);
        //                    }
        //                    // 删除TreeView项
        //                    PathTreeNode tvNode = this.tvPath.SelectedItem as PathTreeNode;
        //                    PathTreeNode deleteNode = null;
        //                    foreach (var item1 in tvNode.Children)
        //                    {
        //                        PathTreeNode n = item1 as PathTreeNode;
        //                        if (n.path == item.FullName)
        //                        {
        //                            deleteNode = item1 as PathTreeNode;
        //                        }
        //                    }
        //                    if (deleteNode != null)
        //                    {
        //                        tvNode.Children.Remove(deleteNode);
        //                    }

        //                });


        //                StatusBar.print(MessageType.Info, "删除成功");
        //            }));
        //        }
        //        catch (Exception ex)
        //        {
        //            logger.ErrorFormat("文件删除失败：{0}", ex.Message);
        //        }
        //    }));
        //    progressingDlg.WindowStartupLocation = WindowStartupLocation.CenterOwner;
        //    progressingDlg.Owner = this;
        //    progressingDlg.ShowDialog();


        //}

        private void DataConversion_Click(object sender, RoutedEventArgs e)
        {
            //SQLiteHelper sQLite = new SQLiteHelper("C:\\Users\\86159\\Desktop\\TV1600_OSI000_2024-02-22-12-08-19-426.ftms");
            //sQLite.Open();
            //Tuple<bool, SQLiteDataReader, string> res = sQLite.ExecuteReader("select * from vibdata", null);
            //if (res.Item1) // 查询成功
            //{
            //    using (res.Item2)
            //    {
            //        while (res.Item2.Read())
            //        {
            //            Console.WriteLine(res.Item2["measdefid"]);
            //        }
            //    }
            //}
            //sQLite.Close();   
            DataConversionDlg dlg = new DataConversionDlg();
            dlg.Owner = this;
            dlg.WindowStartupLocation= WindowStartupLocation.CenterOwner;
            dlg.Show();
        }


        private void MakeDir_Click(object sender, RoutedEventArgs e)
        {
            //MenuItem munuItem = sender as MenuItem;
            //if (munuItem == null) return;
            //System.Collections.IList items = (munuItem.CommandParameter) as System.Collections.IList;

            //var fileViewModels = items.Cast<FileInfoViewModel>();

            //if (fileViewModels == null||fileViewModels.Count()!=1) return;

            //List<FTPFileInfo> files = new List<FTPFileInfo>();
            ////for (int i = 0; i < fileViewModels.Length; i++)
            ////{
            ////    files.Add(fileViewModels[i].ToInfo());
            ////}
            //foreach (var item in fileViewModels)
            //{
            //    files.Add(item.ToInfo());
            //}

            if (TW_App.ftp == null || !TW_App.ftp.GetConnectStatus())
            {
                MessageBox.Show("SFTP未连接，请连接后操作", "提示", MessageBoxButton.OK, MessageBoxImage.Information);

                return;
            }

            if (tvPath.SelectedItem == null) {
                MessageBox.Show("请选择文件路径");
                return;
            }
               

            PathTreeNode node = tvPath.SelectedItem as PathTreeNode;
            if(node == null) return;

            EditFileNameDlg dlg = new EditFileNameDlg();//创建新建文件夹窗口
            //Owner属性用于指定对话框的父窗口。设置Owner属性有几个好处：
            //对话框将与其所有者窗口保持相同的主题样式。
            //对话框的所有者窗口打开时，对话框通常不会关闭。
            //对话框通常会显示在所有者窗口的上面。
            dlg.Owner = this;
            //设置了dlg对话框的启动位置。
            //WindowStartupLocation.CenterOwner是一个枚举值，它指定对话框应该在其所有者窗口的中心位置打开。
            dlg.WindowStartupLocation = WindowStartupLocation.CenterOwner;

            //bool?（即 Nullable<bool>）类型的值，表示用户如何关闭对话框。
            bool? result = dlg.ShowDialog();

            if(result == true)
            {
                string fileName = dlg.windowViewModel.fileName;
                string fullName = (node.path + "/" + fileName).Replace("\\", "/");
                try
                {
                    TW_App.ftp.MakeDirectory(node.path,fileName);
                    StatusBar.print(MessageType.Info, "文件夹创建成功"); //状态栏显示

                    PathTreeNode newNode = new PathTreeNode();
                    newNode.Name = fileName;
                    newNode.path = fullName;
                    node.Children.Add(newNode);
                    model.FileInfoViewModel fileInfoViewModel = new model.FileInfoViewModel();
                    fileInfoViewModel.Name = fileName;
                    fileInfoViewModel.FullName = fullName;
                    fileInfoViewModel.Length = 0;
                    fileInfoViewModel.LastWriteTime = DateTime.Now;
                    fileInfoViewModel.LastAccessTime = DateTime.Now;
                    fileInfoViewModel.IsDirectory = true;
                    fileInfoViewModel.IsSelected = false;
                    windowViewModel.CurPaths.Add(fileInfoViewModel);
                }
                catch (Exception)
                {
                    StatusBar.print(MessageType.Error, "文件夹创建失败");
                }
            }
        }

        private void ReName_Click(object sender, RoutedEventArgs e)
        {
            //MenuItem munuItem = sender as MenuItem;
            //if (munuItem == null) return;
            //System.Collections.IList items = (munuItem.CommandParameter) as System.Collections.IList;
            if (TW_App.ftp == null || !TW_App.ftp.GetConnectStatus())
            {
                MessageBox.Show("SFTP未连接，请连接后操作", "提示", MessageBoxButton.OK, MessageBoxImage.Information);

                return;
            }
            var fileViewModels = lvPath.SelectedItems.Cast<model.FileInfoViewModel>();


            if (fileViewModels == null || fileViewModels.Count() != 1) {
                MessageBox.Show("不可不选或多选文件进行重命名","提示");
                StatusBar.print(MessageType.Error, "重命名失败");
                return;
            }

            model.FileInfoViewModel f = fileViewModels.FirstOrDefault();
            if (f == null) return;

            EditFileNameDlg dlg = new EditFileNameDlg();
            dlg.Owner = this;
            dlg.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            dlg.windowViewModel.fileName = f.Name;//显示未修改文件名

            bool? result = dlg.ShowDialog();

            if (result == true)
            {
                //dlg.tbFileName.Text = "222";
                string name = dlg.windowViewModel.fileName;
                if (name == null) {
                    MessageBox.Show("文件名不能为空");
                    StatusBar.print(MessageType.Error, "重命名失败");
                    return; }
                try
                {
                    string newName = f.FullName.Replace(f.Name, name);
                    
                    TW_App.ftp.Rename(f.FullName, newName);
                    StatusBar.print(MessageType.Info, "重命名成功");

                    // 改TreeView中的文件名
                    PathTreeNode pNode = this.tvPath.SelectedItem as PathTreeNode;
                    if(pNode != null)
                    {
                        PathTreeNode editNode = null;
                        foreach (PathTreeNode item in pNode.Children)
                        {
                            if(item.path.Equals(f.FullName)){
                                editNode = item;
                                break;
                            }
                        }
                        if (editNode != null)
                        {
                            editNode.path = newName;
                            editNode.Name = name;
                            editNode.IsExpanded = false;
                            editNode.ChildReset();
                        }
                    }


                    // 改ListView中的文件名
                    f.FullName = newName;
                    f.Name = name;
                }
                catch (Exception)
                {
                    StatusBar.print(MessageType.Error, "重命名失败");
                }

            }
        }

        private void ListViewItem_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;
        }

        private void Previous_Click(object sender, RoutedEventArgs e)
        {
            // 判断SFTP是否为连接状态，如果未连接则退出
            if (TW_App.ftp == null || !TW_App.ftp.GetConnectStatus())
            {
                MessageBox.Show("SFTP未连接，请连接后操作", "提示", MessageBoxButton.OK, MessageBoxImage.Information);

                return;
            }

            // 判断目录树是否有被选中节点，没有则退出
            if (this.tvPath.SelectedItem == null) return;
            
            // 将控件选中的节点转换未PathTreeNode类型
            PathTreeNode curNode = this.tvPath.SelectedItem as PathTreeNode;
            if (curNode == null) return;  // 如果转换失败，直接退出
            if (curNode == windowViewModel.RootNode) {
                MessageBox.Show("到达根节点");
                return; } // 如果当前选中节点等于根节点，直接退出

            curNode.IsSelected = false;
            curNode.ParentNode.IsSelected = true;

            RefreshListView(curNode.ParentNode);

        }

        private void CheckBox_Checked(object sender, RoutedEventArgs e)
        {
            lvPath.SelectedItems.Clear();
            foreach (model.FileInfoViewModel item in windowViewModel.CurPaths)
            {
                item.IsSelected = true;
                lvPath.SelectedItems.Add(item);
            }
        }

        private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            lvPath.SelectedItems.Clear();
            foreach (model.FileInfoViewModel item in windowViewModel.CurPaths)
            {
                item.IsSelected = false;
            }
        }

        #endregion

        #region 处理函数
        /// <summary>
        /// 根据树节点刷新文件列表
        /// </summary>
        /// <param name="node"></param>
        private void RefreshListView(PathTreeNode node)
        {
            if(node == null) return;

            // 清空文件列表
            windowViewModel.CurPaths.Clear();
            try
            {
                if (TW_App.ftp == null || !TW_App.ftp.GetConnectStatus())
                {
                    MessageBox.Show("SFTP未连接，请连接后操作", "提示", MessageBoxButton.OK, MessageBoxImage.Information);

                    return;
                }

                List<FTPFileInfo> files = TW_App.ftp.GetFileInfoList(node.path);
                ObservableCollection<model.FileInfoViewModel> infos = new ObservableCollection<model.FileInfoViewModel>();
                foreach (FTPFileInfo file in files)
                {
                    if (".".Equals(file.Name) || "..".Equals(file.Name))
                        continue;
                    infos.Add(new model.FileInfoViewModel(file));
                }
                windowViewModel.CurPaths = new ObservableCollection<model.FileInfoViewModel>(infos.OrderByDescending(item => item.IsDirectory));
            }
            catch (Exception)
            {

            }
        }

        /*
         * 获得指定路径下所有文件名
         * StreamWriter sw  文件写入流
         * string path      文件路径
         * int indent       输出时的缩进量
         */
        public static void getFileName(List<string> files, string path)
        {
            DirectoryInfo root = new DirectoryInfo(path);
            foreach (FileInfo f in root.GetFiles())
            {
                files.Add(f.FullName);
            }
        }

        //获得指定路径下所有子目录名
        public static void getDirectory(List<string> files, string path)
        {
            getFileName(files, path);
            DirectoryInfo root = new DirectoryInfo(path);
            foreach (DirectoryInfo d in root.GetDirectories())
            {
                files.Add(d.FullName);
                getDirectory(files, d.FullName);
            }
        }
        #endregion

    }

    public class MainWindowViewModel : ViewModelBase
    {
        public MainWindowViewModel()
        {
            title = TW_App.PROJECT_NAME + " v" + TW_App.VERSION;

            connectInfo = new ConnectInfoViewModel();

            TreeNodes = new ObservableCollection<PathTreeNode>();
            RootNode = new PathTreeNode();
            RootNode.Name = "根目录";
            RootNode.path = TW_App.globalSetting.rootPath;
            TreeNodes.Add(RootNode);
            CurPaths = new ObservableCollection<model.FileInfoViewModel>();

            toolBarLinkIp = "未连接";
        }

        public int Load()
        {
            int rn = 0;
            
            return rn;
        }
        /// <summary>
        /// 重新加载
        /// </summary>
        /// <returns></returns>
        public int ReLoad()
        {
            int rn = 0;
            RootNode.path = TW_App.globalSetting.rootPath;
            RootNode.IsSelected = false;
            RootNode.IsExpanded = false;
            RootNode.Reset();
            CurPaths.Clear();
            return rn;
        }

        private string m_title;
        public string title
        {
            get { return m_title; }
            set
            {
                m_title = value;
                NotifyPropertyChanged();
            }
        }

        private PathTreeNode m_RootNode;
        public PathTreeNode RootNode
        {
            get { return m_RootNode; }
            set
            {
                m_RootNode = value;
            }
        }

        private PathTreeNode m_curPathNode;
        public PathTreeNode curPathNode
        {
            get { return m_curPathNode; }
            set
            {
                m_curPathNode = value;
                if (value != null)
                {
                    if (TW_App.globalSetting.rootPath.Equals("/"))
                    {
                        curPath = curPathNode.path;
                    }
                    else
                    {
                        curPath = curPathNode.path.Replace(TW_App.globalSetting.rootPath, "");
                    }
                    
                    if (string.IsNullOrEmpty(curPath))
                    {
                        curPath = "/";
                    }
                }

                NotifyPropertyChanged();
            }
        }

        private string m_curPath;
        public string curPath
        {
            get { return m_curPath; }
            set
            {
                m_curPath = value;
                NotifyPropertyChanged();
            }
        }


        private ObservableCollection<PathTreeNode> m_TreeNodes;
        public ObservableCollection<PathTreeNode> TreeNodes
        {
            get { return this.m_TreeNodes; }
            set
            {
                this.m_TreeNodes = value;
                NotifyPropertyChanged();
            }
        }

        private ObservableCollection<model.FileInfoViewModel> m_CurPaths;
        public ObservableCollection<model.FileInfoViewModel> CurPaths
        {
            get { return this.m_CurPaths; }
            set
            {
                this.m_CurPaths = value;
                NotifyPropertyChanged();
            }
        }

        private ConnectInfoViewModel m_connectInfo;
        public ConnectInfoViewModel connectInfo
        {
            get { return m_connectInfo; }
            set
            {
                m_connectInfo = value;
                NotifyPropertyChanged();
            }
        }

        private string m_tooBarLinkIp;
        public string toolBarLinkIp
        {
            get { return m_tooBarLinkIp; }
            set
            {
                m_tooBarLinkIp = value;
                NotifyPropertyChanged();
            }
        }

    }
}
